package Serveur;
import GUI.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

/*********************************************
* Un squelette de serveur TCP Multi-Processus.
*
* Yann & JC
* INSA TOULOUSE
**********************************************/
public class ComunicaTCPServer extends Thread {
    static BufferedWriter out;
    static BufferedReader in;
    ServerSocket server;
    Socket client;
    int port;
    
    
    public ComunicaTCPServer(int port)  {
        this.port=port; 
        try
        {
            System.out.println("Serveur TCP sur le port "+port+"...");
            ServerSocket srv=new ServerSocket(port);
            //while(true)
            //{
                Socket client=srv.accept();
                run(client);
            //}
        }
        catch(Exception e)
        {
            System.err.println("Arret du serveur.");
            System.err.println(e);
        }
    }
    
    ///////////////////////////////////////////////
    public void run(Socket client)
    {
        System.out.println("Connexion depuis "+client.getInetAddress()+":"+client.getPort()+"...");
        initStreams(client);
    }
    ///////////////////////////////////////////////
    ///////////////////////////////////////////////
    public void initStreams(Socket s)
    {
        try
        {
            client=s;
            out= new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
            in= new BufferedReader(new InputStreamReader(client.getInputStream()));
            this.start();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    ///////////////////////////////////////////////
    ///////////////////////////////////////////////
    
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
               new ComunicaTCPServer(4444);
               new Comunica("TD4_serveur",in,out).setVisible(true);
               //new Comunica("TD3_B",in2,out2).setVisible(true);
            }
        });
    }
    
}